//
//  RMMOderAdressViewController.m
//  Romomo
//
//  Created by puman on 16/10/12.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMOderAdressViewController.h"
#import "RMMAdressTableViewCell.h"
#import "RMMAddNewAdressViewController.h"
#import "RMMAdressView.h"
#import "RMMChosseDateViewController.h"
#import "RMMShopingModel.h"
#import "RMMStoresTableViewCell.h"
#import "RMMChooseSkillViewController.h"

@interface RMMOderAdressViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMOderAdressViewController
{
    RMMAdressView *_adreView;
    RMMNotNetWorkView *_networkView;
    UIButton *_bottomBut;
    UITableView *_tableView;
    UIView *_footView;
    NSMutableArray *_dataArray;
    NSInteger _butTag;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    if (_titleName.length) {
        self.navigationItem.title = @"我的地址";
    } else {
        if ([_isHome isEqualToString:@"1"]) {
            self.navigationItem.title = @"请选择上门服务地址";
        } else {
            self.navigationItem.title = @"请选择到店服务地址";
        }
    }
    [self addViews];
    [self getRequestData];
    // Do any additional setup after loading the view.
}
- (void)dealloc{
    [RMMFileManager shareHandle].fromSkillType = @"0";
}
- (void)getRequestData{
    [_dataArray removeAllObjects];
    if (_titleName.length) {
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
        parDic[@"org_no"] = Org_no;
        parDic[@"cust_id"] = cust_id;
        NSString *url = GetAddessUrl;
        [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
            if (isNetwork) {
                _networkView.hidden = YES;
            } else {
                _networkView.hidden = NO;
            }
        } method:GET finish:^(NSDictionary *dataDic) {
            NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
            if ([status isEqualToString:@"1"]) {
                _dataArray = dataDic[@"data"];
                if (_dataArray.count == 0) {
                    _tableView.hidden = YES;
                    _adreView.hidden = NO;
                } else {
                    _tableView.hidden = NO;
                    _adreView.hidden = YES;
                }
            } else {
                [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
            }
            [_tableView reloadData];
        } error:^(NSError *errors) {
            
        } view:self.view];
    } else {
        if ([_isHome isEqualToString:@"1"]) {
            NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
            NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
            parDic[@"org_no"] = Org_no;
            parDic[@"cust_id"] = cust_id;
            NSString *url = GetAddessUrl;
            [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
                if (isNetwork) {
                    _networkView.hidden = YES;
                } else {
                    _networkView.hidden = NO;
                }
            } method:GET finish:^(NSDictionary *dataDic) {
                NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    _dataArray = dataDic[@"data"];
                    if (_dataArray.count == 0) {
                        _tableView.hidden = YES;
                        _adreView.hidden = NO;
                    } else {
                        _tableView.hidden = NO;
                        _adreView.hidden = YES;
                    }
                } else {
                    [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
                }
                [_tableView reloadData];
            } error:^(NSError *errors) {
                
            } view:self.view];
        } else {
            NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
            parDic[@"region_id"] = [RMMFileManager shareHandle].region_id;
            NSMutableArray *arrays = [NSMutableArray array];
            for (RMMShopingModel *model in _goodsArray) {
                [arrays addObject:model.SERVICE_ID];
            }
            if (arrays.count == 1) {
                parDic[@"service_list"] = [NSString stringWithFormat:@"%@#",arrays[0]];
                
            } else {
                parDic[@"service_list"] = [arrays componentsJoinedByString:@"#"];
            }
            NSString *url = GetStoresUrl;
            [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
                if (isNetwork) {
                    _networkView.hidden = YES;
                } else {
                    _networkView.hidden = NO;
                }
            } method:GET finish:^(NSDictionary *dataDic) {
                NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    NSArray *array = dataDic[@"data"];
                    for (NSDictionary *dic in array) {
                        RMMStoresModel *model = [[RMMStoresModel alloc] init];
                        [model setValuesForKeysWithDictionary:dic];
                        model.isSelect = @"0";
                        [_dataArray addObject:model];
                    }
                } else {
                    [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
                }
                [_tableView reloadData];
                
            } error:^(NSError *errors) {
                
            } view:self.view];
        }
    }
}
- (void)addViews{
    if ([_isHome isEqualToString:@"1"] || _titleName.length) {
        [self addRightItem];
    }
    _butTag = 0;
    _adreView = [[RMMAdressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    BUTTON_S(_adreView.addBut, addNewAdress);
    [self.view addSubview:_adreView];
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = footView;
    if (_titleName.length) {
        [_tableView registerClass:[RMMAdressTableViewCell class] forCellReuseIdentifier:@"Cells"];
    } else {
        if ([_isHome isEqualToString:@"1"]) {
            [_tableView registerClass:[RMMAdressTableViewCell class] forCellReuseIdentifier:@"Cell"];
        } else {
            [_tableView registerClass:[RMMStoresTableViewCell class] forCellReuseIdentifier:@"StoresCell"];
        }
    }
    [self.view addSubview:_tableView];
    [self addLeftItem];
    
    if (!_titleName.length) {
        _footView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
        _footView.backgroundColor = kWhiteColor;
        [self.view addSubview:_footView];
        
        UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _footView.width, 0.5)];
        lineLabel.backgroundColor = RGBA(221, 221, 221, 1);
        [_footView addSubview:lineLabel];
        
        _bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _bottomBut.frame = CGRectMake(kScreenWideth / 2 - kHalf * 2, 6.5, 4 * kHalf, 36);
        _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
        [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
        _bottomBut.titleLabel.font = kBFont(14);
        _bottomBut.layer.masksToBounds = YES;
        _bottomBut.layer.cornerRadius = 18;
        [_bottomBut setTitle:@"下一步" forState:(UIControlStateNormal)];
        _bottomBut.userInteractionEnabled = NO;
        BUTTON_S(_bottomBut, doneButBackClick);
        
        [_footView addSubview:_bottomBut];
    }
    _dataArray = [NSMutableArray array];
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];
}
- (void)networkBut{
    [self getRequestData];
}
- (void)doneButBackClick{
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        RMMChooseSkillViewController *VC = [[RMMChooseSkillViewController alloc] init];
        [[RMMFileManager shareHandle].bookingDic setValue:_dataArray[_butTag - 1000] forKey:@"地址"];
        VC.isHome = _isHome;
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        RMMChosseDateViewController *VC = [[RMMChosseDateViewController alloc] init];
        if ([_isHome isEqualToString:@"1"]) {
            [[RMMFileManager shareHandle].bookingDic setValue:_dataArray[_butTag - 1000] forKey:@"地址"];
        } else {
            RMMStoresModel *model = _dataArray[_butTag - 1000];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"ADD_NAME"] = model.Store_Name;
            dic[@"MOBILE"] = model.Store_Tel;
            dic[@"DE_ADDRESS"] = model.Store_Address;
            dic[@"PROVINCE_NAME"] = @"";
            dic[@"CITY_NAME"] = @"";
            dic[@"REGION_NAME"] = model.Region_Name;
            dic[@"ID"] = model.Store_ID;
            dic[@"TYPE"] = @0;
            [[RMMFileManager shareHandle].bookingDic setValue:dic forKey:@"地址"];
        }
        VC.type = _type;
        VC.isHome = _isHome;
        [self.navigationController pushViewController:VC animated:YES];
    }
}
- (void)addRightItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:(UIBarButtonItemStylePlain) target:self action:@selector(addNewAdress)];
    self.navigationItem.rightBarButtonItem = item;
    //item.tintColor = kBasicColor;
}
- (void)addLeftItem{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = item;

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_titleName.length) {
        return 75;
    } else {
        if ([_isHome isEqualToString:@"1"]) {
            return 75;
        } else {
            return 110;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_titleName.length) {
        RMMAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cells"];
        if (!_dataArray.count) {
            return cell;
        }
        cell.dic = [RMMFileManager setValueForDic:_dataArray[indexPath.row]];
        cell.number = @1;
        cell.mineSet = @"我的地址";
        cell.editorBut.tag = 1 + indexPath.row;
        cell.button.tag = 1000 + indexPath.row;
        BUTTON_S(cell.button, buttonClick:);
        BUTTON_S(cell.editorBut, editorButClick:)
        return cell;
    } else {
        if ([_isHome isEqualToString:@"1"]) {
            RMMAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            if (!_dataArray.count) {
                return cell;
            }
            cell.dic = [RMMFileManager setValueForDic:_dataArray[indexPath.row]];
            cell.number = @1;
            cell.editorBut.tag = 1 + indexPath.row;
            cell.button.tag = 1000 + indexPath.row;
            BUTTON_S(cell.button, buttonClick:);
            BUTTON_S(cell.editorBut, editorButClick:)
            return cell;
        } else {
            RMMStoresTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoresCell"];
            if (!_dataArray.count) {
                return cell;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _dataArray[indexPath.row];
            cell.selectBUt.tag = 1000 + indexPath.row;
            BUTTON_S(cell.selectBUt, selectBUtClick:);
            BUTTON_S(cell.telBut, telButClick:)
            return cell;
        }
    }
}
- (void)selectBUtClick:(UIButton *)button{
    
}
- (void)telButClick:(UIButton *)but{
    [RMMFileManager  callKeFuWithPhoneNumber:[but titleForState:(UIControlStateNormal)] onView:self.view];
}
- (void)buttonClick:(UIButton *)button{
//    _butTag = button.tag;
//    _bottomBut.backgroundColor = kBasicColor;
//    [_bottomBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
//    _bottomBut.userInteractionEnabled = YES;
//    for (int i = 0; i < _dataArray.count; i++) {
//        UIButton *buttons = [self.view viewWithTag:1000 + i];
//        [buttons setImage:[UIImage imageNamed:@"可选@2x"] forState:(UIControlStateNormal)];
//        if (buttons.tag == _butTag) {
//            [buttons setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
//        }
//    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_isHome isEqualToString:@"1"]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    _butTag = indexPath.row + 1000;
    _bottomBut.backgroundColor = kBasicColor;
    [_bottomBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    _bottomBut.userInteractionEnabled = YES;
    for (int i = 0; i < _dataArray.count; i++) {
        UIButton *buttons = [self.view viewWithTag:1000 + i];
        [buttons setImage:[UIImage imageNamed:@"可选@2x"] forState:(UIControlStateNormal)];
        if (buttons.tag == _butTag) {
            [buttons setImage:[UIImage imageNamed:@"选中@3x"] forState:(UIControlStateNormal)];
        }
    }
}
- (void)editorButClick:(UIButton *)button{
    RMMAddNewAdressViewController *VC = [[RMMAddNewAdressViewController alloc] init];
    VC.dic = _dataArray[button.tag - 1];
    VC.addNewAdressBlock = ^void(){
        [self getRequestData];
    };
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [self deleteAdressWithAddId:[NSString stringWithFormat:@"%@",_dataArray[indexPath.row][@"ID"]] forRow:indexPath.row];
    }];
    deleteAction.backgroundColor = [UIColor redColor];
    UITableViewRowAction *setAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"设为默认" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self setMoRemAdressWith:_dataArray[indexPath.row]];
    }];
    setAction.backgroundColor = RGBA(228, 155, 56, 1);
    return @[deleteAction,setAction];
}

// 新增地址
- (void)addNewAdress{
    RMMAddNewAdressViewController *VC = [[RMMAddNewAdressViewController alloc] init];
    VC.addNewAdressBlock = ^void(){
        [self getRequestData];
    };
    [self.navigationController pushViewController:VC animated:YES];
}
// 删除地址
- (void)deleteAdressWithAddId:(NSString *)add_id forRow:(NSInteger)row{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"org_no"] = Org_no;
    parDic[@"add_id"] = add_id;
    parDic[@"cust_id"] = CUST_ID;
    NSString *url = DelAddessUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [_dataArray removeObjectAtIndex:row];
            [MMProgressHUD show];
            [MMProgressHUD dismissWithSuccess:@"删除成功!" title:nil afterDelay:1.0];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 设置默认地址
- (void)setMoRemAdressWith:(NSDictionary *)dic{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"add_id"] = dic[@"ID"];
    parDic[@"cust_id"] = CUST_ID;
    parDic[@"org_no"] = Org_no;
    NSString *url = SetMoRenAddUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self getRequestData];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];

}
// 取消
- (void)cancel{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
